﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Threading.Tasks;
using Atmk.WaterMeter.MIS.Commons.Interfaces;
using Atmk.WaterMeter.MIS.Commons.Interfaces.Logic;
using Atmk.WaterMeter.MIS.Commons.Interfaces.Repository;
using Atmk.WaterMeter.MIS.Commons.Utils;
using Atmk.WaterMeter.MIS.Entities;
using Atmk.WaterMeter.MIS.Entities.Enums;
using Atmk.WaterMeter.MIS.Entities.Models;
using Microsoft.EntityFrameworkCore.Internal;
using NLog;

namespace Atmk.WaterMeter.MIS.Logic
{
    /// <summary>
    /// </summary>
    public class DataStoreLogic : IDataStoreLogic
    {
        private readonly Logger _logger = LogManager.GetCurrentClassLogger();
        private readonly IMeterFrozenDataRepository _meterFrozenDataRepository;

        private readonly IRepository _repository;

        /// <inheritdoc />
        public DataStoreLogic(
            IRepository repository,
            IMeterFrozenDataRepository meterFrozenDataRepository
        )
        {
            _repository = repository;
            _meterFrozenDataRepository = meterFrozenDataRepository;
        }

        /// <summary>
        ///     记录水表读数记录数据
        /// </summary>
        /// <param name="meterNumber">水表编码</param>
        /// <param name="serviceData"></param>
        /// <param name="eventTime"></param>
        //public int MeterRecordSave(string meterNumber, DeviceData serviceData, DateTime eventTime)
        //{
        //    //_logger.Info($"保存上传记录{meterNumber} {serviceData} {eventTime}");
        //    try
        //    {
        //        using (var context = Datas.ContextBuilder.Build())
        //        {
        //            //获取最新水表数据
        //            var meters = context.MeterReadingRecord.Where(m => m.Number == meterNumber).OrderByDescending(r => r.ReadTime).Take(100).ToList();
        //            //判断是否重复数据
        //            if (!meters.Any(m => m.ReadTime >= eventTime))
        //            {
        //                double last = 0;
        //                //返回水表最后读数
        //                if (meters.Any()) last = meters.First().Value;
        //                //当前水表读数
        //                var readString = Base64Convert.ConvertBytes(serviceData.current);
        //                var readInt = BytesConvert.BitConvertInts(readString, 6).First();
        //                //创建需要保存的水表数据
        //                var record = new MeterReadingRecord()
        //                {
        //                    Number = meterNumber,
        //                    ReadTime = eventTime,
        //                    Value = readInt / 100.00,
        //                    //LastValue = last,
        //                    Warning = serviceData.warning,
        //                    ValveState = serviceData.valve,
        //                    MsgType = serviceData.msgtype,
        //                    Voltage = (serviceData.voltage + 150) * 0.01,
        //                    //1日冻结数据（每天只发1次 取serviceData.current）2小时冻结 （一组24个数据“，”分割）3月冻结 4抄表当前指令
        //                    Value24Type = (int)Value24Type.one
        //                };
        //                context.MeterReadingRecord.Add(record);

        //                //马贤辉2019-9-1新增
        //                //历史水表读数
        //                var history = BytesConvert.BitConvertInts(Base64Convert.ConvertBytes(serviceData.history), 6);
        //                List<MeterReadingRecord> MRRs = new List<MeterReadingRecord>();
        //                int tt = 0;
        //                //如果 小时历史数据是正序  1，2，3，4 就打开下面注释
        //                //foreach (var item in history.Reverse())
        //                foreach (var item in history)
        //                {
        //                    //判断历史数据前100条中  是否存在该小时数据
        //                    if (!meters.Where(m => m.Value24Type == (int)Value24Type.two && m.ReadTime.ToString("yyyyMMdd HH") == eventTime.AddHours(-tt).ToString("yyyyMMdd HH")).Any())
        //                    {
        //                        var record2 = new MeterReadingRecord
        //                        {
        //                            Number = meterNumber,
        //                            ReadTime = eventTime.AddHours(-tt),
        //                            Value = item / 100.00,
        //                            //LastValue = last,
        //                            //ValveState = serviceData.valve == 1 ? ValveState.Opening : ValveState.Closed,
        //                            ValveState = serviceData.valve,
        //                            MsgType = serviceData.msgtype,
        //                            //Voltage = ((serviceData.voltage + 150) * 0.01).ToString(CultureInfo.CurrentCulture),
        //                            Voltage = (serviceData.voltage + 150) * 0.01,
        //                            //1日冻结数据（每天只发1次 取serviceData.current）2小时冻结 （一组24个数据“，”分割）3月冻结 4抄表当前指令
        //                            Value24Type = (int)Value24Type.two //2历史数据  1当前数据
        //                        };
        //                        MRRs.Add(record2);
        //                    }
        //                    tt++;
        //                }
        //                context.MeterReadingRecord.AddRange(MRRs);
        //                return context.SaveChanges();
        //            }
        //        }

        //        return 0;
        //    }
        //    catch (Exception ex)
        //    {
        //        return 0;
        //    }
        //}

        /// <summary>
        ///     记录小时冻结数据
        /// </summary>
        /// <param name="meterNumber"></param>
        /// <param name="history"></param>
        /// <param name="eventTime"></param>
        //public void HourFrozenSave(string meterNumber, byte[] history, DateTime eventTime)
        //{
        //    const int unitLength = 6;
        //    if (history.Length % unitLength != 0)
        //        throw new Exception($"冻结数据字节长度不是{unitLength}的倍数,数据错误");
        //    //获取小时日冻结数据
        //    var hourFrozens = BytesConvert.BitConvertInts(history, unitLength);
        //    //获取小时冻结数据获取的标识日期数据
        //    var date = eventTime.AddHours(-hourFrozens.Count).Date;
        //    var recordFrozen =
        //        _meterFrozenDataRepository.FrozenDatas(meterNumber, date, FrozenType.Hour);
        //    //添加记录的缓存
        //    var recordAdd = new List<FrozenDataRecord>();
        //    for (var i = 0; i < hourFrozens.Count; i++)
        //    {
        //        var checkdt = eventTime.AddHours(-(i + 1));
        //        if (recordFrozen.Any(r => r.FrozenDate == checkdt.Date && r.Unit == checkdt.Hour)) continue;
        //        var newFrozen = new FrozenDataRecord
        //        {
        //            Number = meterNumber,
        //            FrozenType = FrozenType.Hour,
        //            FrozenDate = checkdt.Date,
        //            Unit = checkdt.Hour,
        //            FrozenRead = (int)hourFrozens[i] / 100,
        //            FrozenRecord = $"{hourFrozens[i] / 100.00}"
        //        };
        //        recordAdd.Add(newFrozen);
        //    }

        //    _repository.AddRang(recordAdd.ToArray());
        //}

        /// <summary>
        ///     记录日冻结数据
        /// </summary>
        /// <param name="meterNumber"></param>
        /// <param name="history"></param>
        /// <param name="eventTime"></param>
        //public void DayFrozenSave(string meterNumber, byte[] history, DateTime eventTime)
        //{
        //    if (history.Length % 4 != 0)
        //        throw new Exception("冻结数据字节长度不是4的倍数,数据错误");
        //    //获取日冻结数据
        //    var frozens = BytesConvert.BitConvertInts(history, 4);
        //    //获取日冻结数据获取的标识日期数据最远日期
        //    var date = eventTime.AddDays(-frozens.Count).Date;
        //    var recordFrozen =
        //        _meterFrozenDataRepository.FrozenDatas(meterNumber, date, FrozenType.Day);
        //    //添加记录的缓存
        //    var recordAdd = new List<FrozenDataRecord>();
        //    for (var i = 0; i < frozens.Count; i++)
        //    {
        //        var checkdt = eventTime.AddDays(-(i + 1));
        //        if (recordFrozen.Any(r => r.FrozenDate == checkdt.Date && r.Unit == checkdt.Day)) continue;
        //        var newFrozen = new FrozenDataRecord
        //        {
        //            Number = meterNumber,
        //            FrozenType = FrozenType.Day,
        //            FrozenDate = checkdt.Date,
        //            Unit = checkdt.Day,
        //            FrozenRead = (int)frozens[i] / 100,
        //            FrozenRecord = $"{frozens[i] / 100.00}"
        //        };
        //        recordAdd.Add(newFrozen);
        //    }

        //    _repository.AddRang(recordAdd.ToArray());
        //}

        /// <summary>
        ///     记录月冻结数据
        /// </summary>
        /// <param name="meterNumber"></param>
        /// <param name="history"></param>
        /// <param name="eventTime"></param>
        //public void MonthFrozenSave(string meterNumber, byte[] history, DateTime eventTime)
        //{
        //    if (history.Length % 4 != 0)
        //        throw new Exception("冻结数据字节长度不是4的倍数,数据错误");
        //    //获取月冻结数据
        //    var frozens = BytesConvert.BitConvertInts(history, 4);
        //    //获取月冻结数据获取的标识日期数据最远日期
        //    var date = eventTime.AddMonths(-frozens.Count).Date;
        //    var recordFrozen =
        //        _meterFrozenDataRepository.FrozenDatas(meterNumber, date, FrozenType.Month);
        //    //添加记录的缓存
        //    var recordAdd = new List<FrozenDataRecord>();
        //    for (var i = 0; i < frozens.Count; i++)
        //    {
        //        var checkdt = eventTime.AddMonths(-(i + 1));
        //        if (recordFrozen.Any(r => r.FrozenDate.Year == checkdt.Year && r.Unit == checkdt.Month)) continue;
        //        var newFrozen = new FrozenDataRecord
        //        {
        //            Number = meterNumber,
        //            FrozenType = FrozenType.Month,
        //            FrozenDate = checkdt.Date,
        //            Unit = checkdt.Month,
        //            FrozenRead = (int)frozens[i] / 100,
        //            FrozenRecord = $"{frozens[i] / 100.00}"
        //        };
        //        recordAdd.Add(newFrozen);
        //    }

        //    _repository.AddRang(recordAdd.ToArray());
        //}
    }
}